package com.kuizii.base.common.idgenerator;

import org.apache.commons.lang3.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class BaseGenerator extends NodeDistribute implements IdGenerator<String> {

    private long nodeId = 0;

    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    long lastSeconds = 0L;

    private final AtomicLong sequence = new AtomicLong(0L);

    public void setDateTimeFormatter(DateTimeFormatter dateTimeFormatter) {
        this.dateTimeFormatter = dateTimeFormatter;
    }


    @Override
    public String newId() {

        if (TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()) == lastSeconds) {
            sequence.incrementAndGet();
        } else {
            lastSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
            sequence.set(0L);
        }
        String now = LocalDateTime.now().format(dateTimeFormatter);
        return now + StringUtils.leftPad(String.valueOf(nodeId), 3, '0') + sequence;
    }
}
